<?php

namespace app\controller;

use support\Request;
use Intervention\Image\ImageManager as Image;
use Intervention\Image\Drivers\Gd\Driver;

class IndexController
{
    public function index(Request $request)
    {
        $manager = new Image(new Driver());
        if ($request->method() == "POST") {
            $param = $request->all();
            $files = $request->file();
            $arr = [];
            foreach ($files as $k => $v) {
                if ($v->isValid()) {
                    $fileName = $param["path"]
                        . DIRECTORY_SEPARATOR
                        . $param["prefix"]
                        . $v->getUploadName();

                    $file = $v->move($fileName);
                    if ($file) {
                        $manager->read($fileName)->encodeByExtension(quality: (int)$param["strength"])->save($fileName);
                        $arr = [
                            "code" => 1,
                            "msg" => "压缩成功",
                            "file" => $fileName,
                            "data" => $v
                        ];
                    } else {
                        $arr = [
                            "code" => 2,
                            "msg" => "压缩失败",
                            "file" => $fileName,
                            "data" => $v
                        ];
                    }
                } else {
                    $arr = [
                        "code" => 2,
                        "msg" => "无效文件",
                        "file" => "",
                        "data" => $v
                    ];
                }
            }
            return json($arr);
        }
        return view("index/index");
    }

    public function opendir(Request $request)
    {
        $path = $request->get("path");
        if (isset($path)) {
            $command = "explorer.exe $path";
            shell_exec($command);
            return json(["code" => 0, "msg" => "成功"]);
        } else {
            return json(["code" => 2, "msg" => "发生错误"]);
        }
    }
}
